package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sky.dto.DashboardTrendDTO;
import com.sky.entity.Document;
import com.sky.entity.Order;
import com.sky.entity.Merchant;
import com.sky.entity.Student;
import com.sky.mapper.DocumentMapper;
import com.sky.mapper.MerchantMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.StudentMapper;
import com.sky.service.DashboardService;
import com.sky.service.DocumentService;
import com.sky.service.MerchantService;
import com.sky.service.OrderService;
import com.sky.vo.DashboardStatisticsVO;
import com.sky.vo.DashboardTrendDataVO;
import com.sky.vo.DashboardRecentOrderVO;
import com.sky.vo.DashboardTopDocumentVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;

/**
 * 工作台服务实现类
 */
@Service
public class DashboardServiceImpl implements DashboardService {
    private static final Logger log = LoggerFactory.getLogger(DashboardServiceImpl.class);
    
    @Autowired
    private MerchantService merchantService;
    
    @Autowired
    private OrderService orderService;
    
    @Autowired
    private DocumentService documentService;
    
    @Autowired
    private StudentMapper studentMapper;
    
    @Autowired
    private MerchantMapper merchantMapper;
    
    @Autowired
    private OrderMapper orderMapper;
    
    @Autowired
    private DocumentMapper documentMapper;
    
    /**
     * 获取工作台统计数据
     * @return 统计数据
     */
    @Override
    public DashboardStatisticsVO getDashboardStatistics() {
        // 获取商家总数
        Integer merchantCount = merchantMapper.selectCount(null);
        
        // 获取学生总数
        Long studentCountLong = studentMapper.selectCount(null);
        Integer studentCount = studentCountLong != null ? studentCountLong.intValue() : 0;
        
        // 获取订单总数
        Long orderCountLong = orderMapper.selectCount(null);
        Integer orderCount = orderCountLong != null ? orderCountLong.intValue() : 0;
        
        // 获取文档总数
        Long documentCountLong = documentMapper.selectCount(null);
        Integer documentCount = documentCountLong != null ? documentCountLong.intValue() : 0;
        
        // 获取今日订单数和今日销售额
        Map<String, Object> orderStats = orderService.getOrderStats();
        Integer todayOrderCount = 0;
        BigDecimal todaySalesAmount = BigDecimal.ZERO;
        
        if (orderStats != null) {
            if (orderStats.containsKey("todayOrders")) {
                Object todayOrdersObj = orderStats.get("todayOrders");
                if (todayOrdersObj instanceof Long) {
                    todayOrderCount = ((Long) todayOrdersObj).intValue();
                } else if (todayOrdersObj instanceof Integer) {
                    todayOrderCount = (Integer) todayOrdersObj;
                }
            }
            if (orderStats.containsKey("todayAmount")) {
                Object todayAmountObj = orderStats.get("todayAmount");
                if (todayAmountObj instanceof BigDecimal) {
                    todaySalesAmount = (BigDecimal) todayAmountObj;
                }
            }
        }
        
        return new DashboardStatisticsVO(
                merchantCount,
                studentCount,
                orderCount,
                documentCount,
                todayOrderCount,
                todaySalesAmount
        );
    }
    
    /**
     * 获取工作台趋势数据
     * @param trendDTO 时间范围参数
     * @return 趋势数据列表
     */
    @Override
    public List<DashboardTrendDataVO> getDashboardTrendData(DashboardTrendDTO trendDTO) {
        List<DashboardTrendDataVO> trendData = new ArrayList<>();
        
        // 默认使用最近7天的数据
        String timeRange = trendDTO != null && trendDTO.getTimeRange() != null ? 
                trendDTO.getTimeRange() : "week";
        
        LocalDate now = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd");
        
        // 累计计数器
        int cumulativeMerchantCount = 0;
        int cumulativeStudentCount = 0;
        int cumulativeOrderCount = 0;
        BigDecimal cumulativeSalesAmount = BigDecimal.ZERO;
        
        switch (timeRange) {
            case "today":
                // 今日数据（按小时）
                for (int i = 0; i < 24; i++) {
                    String hour = i < 10 ? "0" + i : String.valueOf(i);
                    LocalDateTime startTime = LocalDateTime.of(now, java.time.LocalTime.of(i, 0));
                    LocalDateTime endTime = LocalDateTime.of(now, java.time.LocalTime.of(i, 59, 59));
                    
                    // 每次循环创建新的params对象，避免参数污染
                    Map<String, Object> params = new HashMap<>();
                    params.put("startDate", startTime);
                    params.put("endDate", endTime);
                    
                    // 查询订单数和销售额（指定使用order_time字段）
                    params.put("dateField", "order_time");
                    Long orderCount = orderMapper.selectCountByDateRange(params);
                    BigDecimal salesAmount = orderMapper.selectTotalAmountByDateRange(params);
                    
                    // 查询商家数和学生数（指定使用created_at字段）
                    Map<String, Object> userParams = new HashMap<>();
                    userParams.put("startDate", startTime);
                    userParams.put("endDate", endTime);
                    userParams.put("dateField", "created_at");
                    Long merchantCount = merchantMapper.selectCountByDateRange(userParams);
                    Long studentCount = studentMapper.selectCountByDateRange(userParams);
                    
                    // 计算累计数量
                    cumulativeMerchantCount += (merchantCount != null ? merchantCount.intValue() : 0);
                    cumulativeStudentCount += (studentCount != null ? studentCount.intValue() : 0);
                    cumulativeOrderCount += (orderCount != null ? orderCount.intValue() : 0);
                    cumulativeSalesAmount = cumulativeSalesAmount.add(salesAmount != null ? salesAmount : BigDecimal.ZERO);
                    
                    trendData.add(new DashboardTrendDataVO(
                            hour + ":00",
                            cumulativeMerchantCount,
                            cumulativeStudentCount,
                            cumulativeOrderCount,
                            cumulativeSalesAmount
                    ));
                }
                break;
            case "week":
                // 最近7天数据
                for (int i = 6; i >= 0; i--) {
                    LocalDate date = now.minusDays(i);
                    LocalDateTime startTime = date.atStartOfDay();
                    LocalDateTime endTime = date.plusDays(1).atStartOfDay().minusSeconds(1);
                    
                    // 每次循环创建新的params对象，避免参数污染
                    Map<String, Object> params = new HashMap<>();
                    params.put("startDate", startTime);
                    params.put("endDate", endTime);
                    
                    // 查询订单数和销售额（指定使用order_time字段）
                    params.put("dateField", "order_time");
                    Long orderCount = orderMapper.selectCountByDateRange(params);
                    BigDecimal salesAmount = orderMapper.selectTotalAmountByDateRange(params);
                    
                    // 查询商家数和学生数（指定使用created_at字段）
                    Map<String, Object> userParams = new HashMap<>();
                    userParams.put("startDate", startTime);
                    userParams.put("endDate", endTime);
                    userParams.put("dateField", "created_at");
                    Long merchantCount = merchantMapper.selectCountByDateRange(userParams);
                    Long studentCount = studentMapper.selectCountByDateRange(userParams);
                    
                    // 计算累计数量
                    cumulativeMerchantCount += (merchantCount != null ? merchantCount.intValue() : 0);
                    cumulativeStudentCount += (studentCount != null ? studentCount.intValue() : 0);
                    cumulativeOrderCount += (orderCount != null ? orderCount.intValue() : 0);
                    cumulativeSalesAmount = cumulativeSalesAmount.add(salesAmount != null ? salesAmount : BigDecimal.ZERO);
                    
                    trendData.add(new DashboardTrendDataVO(
                            date.format(formatter),
                            cumulativeMerchantCount,
                            cumulativeStudentCount,
                            cumulativeOrderCount,
                            cumulativeSalesAmount
                    ));
                }
                break;
            case "month":
                // 最近30天数据
                for (int i = 29; i >= 0; i--) {
                    LocalDate date = now.minusDays(i);
                    // 每3天显示一个数据点，避免数据过多
                    if (i % 3 == 0) {
                        LocalDateTime startTime = date.atStartOfDay();
                        LocalDateTime endTime = date.plusDays(1).atStartOfDay().minusSeconds(1);
                        
                        // 每次循环创建新的params对象，避免参数污染
                        Map<String, Object> params = new HashMap<>();
                        params.put("startDate", startTime);
                        params.put("endDate", endTime);
                        
                        // 查询订单数和销售额（指定使用order_time字段）
                        params.put("dateField", "order_time");
                        Long orderCount = orderMapper.selectCountByDateRange(params);
                        BigDecimal salesAmount = orderMapper.selectTotalAmountByDateRange(params);
                        
                        // 查询商家数和学生数（指定使用created_at字段）
                        Map<String, Object> userParams = new HashMap<>();
                        userParams.put("startDate", startTime);
                        userParams.put("endDate", endTime);
                        userParams.put("dateField", "created_at");
                        Long merchantCount = merchantMapper.selectCountByDateRange(userParams);
                        Long studentCount = studentMapper.selectCountByDateRange(userParams);
                        
                        // 计算累计数量
                        cumulativeMerchantCount += (merchantCount != null ? merchantCount.intValue() : 0);
                        cumulativeStudentCount += (studentCount != null ? studentCount.intValue() : 0);
                        cumulativeOrderCount += (orderCount != null ? orderCount.intValue() : 0);
                        cumulativeSalesAmount = cumulativeSalesAmount.add(salesAmount != null ? salesAmount : BigDecimal.ZERO);
                        
                        trendData.add(new DashboardTrendDataVO(
                                date.format(formatter),
                                cumulativeMerchantCount,
                                cumulativeStudentCount,
                                cumulativeOrderCount,
                                cumulativeSalesAmount
                        ));
                    }
                }
                break;
            case "year":
                // 最近12个月数据
                for (int i = 11; i >= 0; i--) {
                    LocalDate date = now.minusMonths(i);
                    LocalDateTime startTime = date.withDayOfMonth(1).atStartOfDay();
                    LocalDateTime endTime = date.withDayOfMonth(date.lengthOfMonth()).atTime(23, 59, 59);
                    
                    // 每次循环创建新的params对象，避免参数污染
                    Map<String, Object> params = new HashMap<>();
                    params.put("startDate", startTime);
                    params.put("endDate", endTime);
                    
                    // 查询订单数和销售额（指定使用order_time字段）
                    params.put("dateField", "order_time");
                    Long orderCount = orderMapper.selectCountByDateRange(params);
                    BigDecimal salesAmount = orderMapper.selectTotalAmountByDateRange(params);
                    
                    // 查询商家数和学生数（指定使用created_at字段）
                    Map<String, Object> userParams = new HashMap<>();
                    userParams.put("startDate", startTime);
                    userParams.put("endDate", endTime);
                    userParams.put("dateField", "created_at");
                    Long merchantCount = merchantMapper.selectCountByDateRange(userParams);
                    Long studentCount = studentMapper.selectCountByDateRange(userParams);
                    
                    // 计算累计数量
                    cumulativeMerchantCount += (merchantCount != null ? merchantCount.intValue() : 0);
                    cumulativeStudentCount += (studentCount != null ? studentCount.intValue() : 0);
                    cumulativeOrderCount += (orderCount != null ? orderCount.intValue() : 0);
                    cumulativeSalesAmount = cumulativeSalesAmount.add(salesAmount != null ? salesAmount : BigDecimal.ZERO);
                    
                    trendData.add(new DashboardTrendDataVO(
                            date.format(DateTimeFormatter.ofPattern("yyyy-MM")),
                            cumulativeMerchantCount,
                            cumulativeStudentCount,
                            cumulativeOrderCount,
                            cumulativeSalesAmount
                    ));
                }
                break;
            default:
                // 默认显示最近7天数据
                for (int i = 6; i >= 0; i--) {
                    LocalDate date = now.minusDays(i);
                    LocalDateTime startTime = date.atStartOfDay();
                    LocalDateTime endTime = date.plusDays(1).atStartOfDay().minusSeconds(1);
                    
                    // 每次循环创建新的params对象，避免参数污染
                    Map<String, Object> params = new HashMap<>();
                    params.put("startDate", startTime);
                    params.put("endDate", endTime);
                    
                    // 查询订单数和销售额（指定使用order_time字段）
                    params.put("dateField", "order_time");
                    Long orderCount = orderMapper.selectCountByDateRange(params);
                    BigDecimal salesAmount = orderMapper.selectTotalAmountByDateRange(params);
                    
                    // 查询商家数和学生数（指定使用created_at字段）
                    Map<String, Object> userParams = new HashMap<>();
                    userParams.put("startDate", startTime);
                    userParams.put("endDate", endTime);
                    userParams.put("dateField", "created_at");
                    Long merchantCount = merchantMapper.selectCountByDateRange(userParams);
                    Long studentCount = studentMapper.selectCountByDateRange(userParams);
                    
                    // 计算累计数量
                    cumulativeMerchantCount += (merchantCount != null ? merchantCount.intValue() : 0);
                    cumulativeStudentCount += (studentCount != null ? studentCount.intValue() : 0);
                    cumulativeOrderCount += (orderCount != null ? orderCount.intValue() : 0);
                    cumulativeSalesAmount = cumulativeSalesAmount.add(salesAmount != null ? salesAmount : BigDecimal.ZERO);
                    
                    trendData.add(new DashboardTrendDataVO(
                            date.format(formatter),
                            cumulativeMerchantCount,
                            cumulativeStudentCount,
                            cumulativeOrderCount,
                            cumulativeSalesAmount
                    ));
                }
        }
        
        return trendData;
    }
    
    /**
     * 获取最新订单列表
     * @param limit 获取数量限制
     * @return 最新订单列表
     */
    @Override
    public List<DashboardRecentOrderVO> getRecentOrders(Integer limit) {
        // 默认显示10条
        if (limit == null || limit <= 0) {
            limit = 10;
        }
        
        List<DashboardRecentOrderVO> recentOrders = new ArrayList<>();
        
        // 创建分页对象，查询最新的订单
        IPage<Order> page = new Page<>(1, limit);
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("created_at");
        
        IPage<Order> orderPage = orderMapper.selectPage(page, queryWrapper);
        List<Order> orders = orderPage.getRecords();
        
        // 将Order对象转换为DashboardRecentOrderVO对象
        for (Order order : orders) {
            // 查询商家信息
            Merchant merchant = merchantMapper.selectById(order.getMerchantId());
            String merchantName = merchant != null ? merchant.getName() : "未知商家";
            
            // 查询学生信息
            String studentName = "学生" + order.getStudentId(); // 实际应该通过studentService查询学生姓名
            try {
                if (order.getStudentId() != null) {
                    Student student = studentMapper.selectById(order.getStudentId());
                    if (student != null) {
                        studentName = student.getName();
                    }
                }
            } catch (Exception e) {
                log.error("查询学生信息失败", e);
            }
            
            // 转换订单状态为中文
            String statusText = "未知";
            if (order.getStatus() != null) {
                switch (order.getStatus()) {
                    case "pending": 
                    case "待支付": 
                        statusText = "待支付";
                        break;
                    case "printing": 
                    case "处理中": 
                        statusText = "处理中";
                        break;
                    case "delivered":
                    case "已配送":
                        statusText = "已配送";
                        break;
                    case "completed": 
                    case "已完成": 
                        statusText = "已完成";
                        break;
                    case "cancelled": 
                    case "已取消": 
                    case "已退款": 
                        statusText = "已取消";
                        break;
                }
            }
            
            recentOrders.add(new DashboardRecentOrderVO(
                    order.getOrderNo(),
                    studentName,  // 注意：构造函数参数顺序保持不变
                    merchantName, // 注意：构造函数参数顺序保持不变
                    order.getAmount(),
                    statusText,
                    order.getCreatedAt(),
                    order.getFileName(),
                    order.getCopies()
            ));
        }
        
        return recentOrders;
    }
    
    /**
     * 获取热门文档列表
     * @param limit 获取数量限制
     * @return 热门文档列表
     */
    @Override
    public List<DashboardTopDocumentVO> getTopDocuments(Integer limit) {
        // 默认显示10条
        if (limit == null || limit <= 0) {
            limit = 10;
        }
        
        List<DashboardTopDocumentVO> topDocuments = new ArrayList<>();
        
        // 查询下载次数最多的文档
        IPage<Document> page = new Page<>(1, limit);
        QueryWrapper<Document> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("download_count");
        
        IPage<Document> documentPage = documentMapper.selectPage(page, queryWrapper);
        List<Document> documents = documentPage.getRecords();
        
        // 将Document对象转换为DashboardTopDocumentVO对象
        for (int i = 0; i < documents.size(); i++) {
            Document document = documents.get(i);
            topDocuments.add(new DashboardTopDocumentVO(
                    i + 1,  // 排名
                    document.getTitle(),
                    document.getFileName(),
                    document.getDownloadCount() != null ? document.getDownloadCount() : 0,
                    document.getUploadTime()
            ));
        }
        
        return topDocuments;
    }
    
    /**
     * 生成随机数（保留此方法以兼容可能的其他调用）
     */
    private int getRandomNumber(int min, int max) {
        return new Random().nextInt(max - min + 1) + min;
    }
}